const AdminBiz = require('../../../store/admin_biz_config.js');
const { pageHelper } = require('../helpers/path_import.js');
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { contentStore } = require('../../../store/content_store.js');

Page({

	/**
	 * 页面的初始数据
	 */
	data: {
		
	},

	/**
	 * 生命周期函数--监听页面加载
	 */
	onLoad: async function (options) {
		if (!AdminBiz.isAdmin(this)) return;

		// 创建MobX绑定
		this.storeBindings = createStoreBindings(this, {
			store: contentStore,
			fields: ['formContent', 'isEditing'],
			actions: ['setFormContent', 'getContentFromEditor', 'setEditingStatus', 'getContentDesc']
		});

		let parent = pageHelper.getPrevPage(2);
		if (!parent) return;

		let formContent = parent.data.formContent;
		if (formContent && formContent.length > 0) {
			this.setFormContent(formContent);
		}
	},

	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady: function () {},

	/**
	 * 生命周期函数--监听页面显示
	 */
	onShow: function () {},

	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide: function () {},

	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload: function () {
		// 清理MobX绑定
		this.storeBindings.destroyStoreBindings();
	},

	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh: async function () {

	},

	model: function (e) {
		pageHelper.model(this, e);
	},

	url: function (e) {
		pageHelper.url(e, this);
	},

	bindSaveTap: function (e) {
		// 从编辑器获取内容
		const formContent = this.getContentFromEditor(this.selectComponent("#contentEditor"));

		let parent = pageHelper.getPrevPage(2);
		if (!parent) return;

		// 如果父页面也使用了MobX，应该调用其对应action
		if (parent.setFormContent && typeof parent.setFormContent === 'function') {
			parent.setFormContent(formContent);
			if (parent._setContentDesc && typeof parent._setContentDesc === 'function') {
				parent._setContentDesc();
			}
		} else {
			// 兼容未迁移到MobX的页面
			parent.setData({
				formContent
			}, () => {
				if (parent._setContentDesc && typeof parent._setContentDesc === 'function') {
					parent._setContentDesc();
				}
			});
		}

		wx.navigateBack();
	}
})